using System;
using Games.Frameworks.UIParticle;
using UnityEditor;
using UnityEngine;

namespace Games.Frameworks.Editor
{
    [InitializeOnLoad]
    public class AutoParticles
    {
        // Start is called before the first frame update
        private static UIParticleHelper[] uiParticleHelpers;

        static AutoParticles()
        {
            EditorApplication.update += Update;
            
            //若点击的为UI层，则播放所有EditorPlay中的UI粒子
            Selection.selectionChanged = delegate
            {
                GameObject obj = Selection.activeObject as GameObject;
                if (obj != null)
                {
                    var realParticle = obj.GetComponent<ParticleSystem>();
                    if (realParticle != null)
                    {
                        realParticle.Play();
                        return;
                    }
                    RectTransform rect = obj.GetComponent<RectTransform>();
                    if (rect != null)
                    {
                        uiParticleHelpers = UIParticleManager.instance.GetComponentsInChildren<UIParticleHelper>();
                    }
                    else
                    {
                        uiParticleHelpers = null;
                    }
                }
            };
        }

        //每帧对UI粒子系统进行一个模拟
        static void Update()
        {
            if(uiParticleHelpers==null||uiParticleHelpers.Length==0)
                return;
            for (int i = 0; i < uiParticleHelpers.Length; i++)
            {
                if (uiParticleHelpers[i] != null&&uiParticleHelpers[i].use)
                    uiParticleHelpers[i]?.AutoSimulate(0.00833f);
            }
            SceneView.RepaintAll();
            
        }
    }
}


